<template>
  <div>
    <el-card shadow="never">
      <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
      <ZwTable ref="tableRef" class="table-box" :option="tableOption" :fetch-params="state.searchParams"
        :fetch-api="fetch()" @selection-change="onSelectionChange">
        <template #headerOperate>
          <el-button @click="batchGive" :disabled="selectid.length == 0">批量分配</el-button>
          <el-button @click="batchdel" :disabled="selectid.length == 0">批量放弃</el-button>
          <el-button @click="router.push('/customer/clubManage/commonSea/importDetail')">导入记录</el-button>
          <el-dropdown style="margin-left: 10px">
            <el-button type="primary">
              添加线索<el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="personAdd">单个添加</el-dropdown-item>
                <el-dropdown-item @click="openExport">批量导入</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </ZwTable>
    </el-card>
    <Dialog :appDialog="appDialog">
      <div class="allcontent">
        <div class="content">
          <div :class="[clubChoose == 1 ? 'column both' : 'column']" @click="clubChoose = 1"><img
              src="@/assets/customer/person.png" /><span class="text">个人线索</span></div>
          <div :class="[clubChoose == 2 ? 'column both' : 'column']" @click="clubChoose = 2"><img
              src="@/assets/customer/customer.png" /><span class="text">企业线索</span></div>
        </div>
      </div>
      <div class="tiptext">
        <el-checkbox v-model="ischecked">勾选之后，将不再提醒</el-checkbox>
      </div>
    </Dialog>
    <NewClub :open="open" :seas_id="props.seaId" :isEdit="isEdit" :rowid="rowid" @close="closeNewClub"
      @submit="submitData"></NewClub>
    <Dialog :appDialog="secondDialog">
      <div class="dialog_content">{{ alertTips }}</div>
    </Dialog>

    <!-- 放弃弹框 -->
    <Dialog :appDialog="abandonDialog">
      <div class="abandon">
        <div class="photo"><img src="@/assets/customer/warn.png" /></div>
        <div class="abandonstyle">
          <div style="margin-bottom: 16px">放弃线索后，线索将不能被员工认领、不能被公海分配和回收</div>
          <el-form :model="abandonData" label-width="auto">
            <el-form-item label="放弃原因" required>
              <el-select v-model="abandonData.invalid_id" placeholder="请选择放弃原因">
                <el-option :label="item.name" :value="item.id" v-for="(item, index) in reasonListData"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </Dialog>
    <ZWDepart ref="DepartRef" @submit="getDepart" type="1" />
    <ClubDrew :clubopen="clubopen" :rowid="rowid" :title="title" @close="close"></ClubDrew>
    <AddBatch :isopen="isopenBatch" :seas_id="props.seaId" @close="isopenBatch = false" @submit="reset()"></AddBatch>
  </div>
</template>
<script setup lang="tsx">
import { ref, reactive, computed, withDefaults, watch } from 'vue'
  import { ElLoading, ElMessage, rowProps } from 'element-plus'
  import ZwTable from '@/components/zw/table/Table'
  import ZwSearchForm from '@/components/zw/search-form/SearchForm'
  import ZWDepart from '@/components/ZWDepart.vue'
  import Dialog from '@/components/Dialog.vue'
  import NewClub from './NewClub.vue'
  import ClubDrew from './ClubDrew.vue'
  import AddBatch from './AddBatch.vue'

  import { unassigned, getDisaled, setSettings, getSettings, delData, setAbandon, reasonList, distribution, flowData } from '@/api/customer/clubManage/commonSea'
  import { getSetionId } from '@/utils/utils'
  import { deepCopy } from '@/utils/helper'
  import router from '@/router'
  // const props = defineProps(['seas_id'])
  const tableRef = ref<HTMLElement | null>(null)
  const defaultParams = {}
  const state = reactive({
    searchParams: deepCopy(defaultParams)
  })
  const DepartRef = ref(null)
  const abandonData = reactive({ invalid_id: '' })
  let selectid = ref([])
  let reasonListData = ref([])
  let isopenBatch = ref(false) //判断批量添加弹框是否打开
  let isbatchDel = ref(false) //判断是否是批量删除
  let isEdit = ref(false) //点击新增个人线索打开新增线索为false 表格操作栏点击编辑为false
  const open = ref(false)
  const clubopen = ref(false) //流转记录抽屉是否打开
  const ischecked = ref(false)
  const clubChoose = ref(0)
  const rowid = ref(null) //行线索id
  const singleStaff = ref([]) //行分配员工
  const batchStaff = ref([]) //批量分配员工
  const whichOpen = ref(1) //判断打开那个员工组件 1为行员工组件 2为批量员工组件
  let title = ref('')
  const assignData = reactive({ clue_list: [], work_user_list: [] })


interface PropsType {
  seaId?: (string | number),
  activeLabel?: number
}

const props = withDefaults(defineProps<PropsType>(), {
  seaId: '',
  activeLabel: 0
})

watch(() => props.activeLabel, (val) => {
  switch(val){ 
    case 0:
    console.log('val 00000- - -   ', val)
    break;
    case 1:
    console.log('val 11111- - -   ', val)
    break;
    case 2:
    console.log('val 22222- - -   ', val)
    break;
  }
}, {immediate: true})


  const cancelHandel = () => {
    appDialog.visible = false
  }
  const submitHandel = () => {
    if (!clubChoose.value) {
      ElMessage.warning('请选择线索类型')
    } else if (clubChoose.value == 1) {
      // 选择个人类型
      setClub(clubChoose.value)
      appDialog.visible = false
      open.value = true
    } else {
      // 选择客户类型
      setClub(clubChoose.value)
    }
  }
  const setClub = (data: any) => {
    setSettings({ clue_type: data, remember: ischecked.value })
  }
  const appDialog = reactive({
    visible: false,
    title: '选择线索类型',
    width: '500px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
  })
  const alertTips = ref('')
  const submitSecond = () => {
    delData({ clue_list: [rowid.value] }).then((res) => {
      secondDialog.visible = false
      ElMessage.success('删除成功')
      reset()
    })
  }
  const cancelSecond = () => {
    secondDialog.visible = false
  }
  const secondDialog = reactive({
    visible: false,
    title: '删除提醒',
    width: '500px',
    cancel: cancelSecond,
    submit: submitSecond,
    cancelText: '取消',
    submitText: '确定'
  })
  const submitAbandon = () => {
    if (!abandonData.invalid_id) {
      ElMessage.warning('请选择放弃原因')
      return
    }
    if (!isbatchDel.value) {
      setAbandon({ clue_list: [rowid.value], invalid_id: abandonData.invalid_id }).then((res) => {
        abandonDialog.visible = false
        ElMessage.success('放弃成功')
        reset()
      })
    } else {
      setAbandon({ ...abandonData, clue_list: selectid.value }).then((res) => {
        abandonDialog.visible = false
        ElMessage.success('放弃成功')
        reset()
      })
    }
  }
  const cancelAbandon = () => {
    abandonDialog.visible = false
  }
  const abandonDialog = reactive({
    visible: false,
    title: '删除提醒',
    width: '500px',
    cancel: cancelAbandon,
    submit: submitAbandon,
    cancelText: '取消',
    submitText: '确定'
  })

  let tableOption = [
    {
      type: 'selection',
      width: 55,
      fixed: 'left'
    },
    {
      prop: 'mobile',
      label: '手机号',
      width: 125,
    },
    {
      prop: 'name',
      label: '线索名称'
    },
    {
      label: '线索类型',
      prop: 'type',
      width: 200,
      render({ row, column, index }) {
        if (row.type == 1) {
          return '个人线索'
        } else {
          return '企业线索'
        }
      }
    },
    {
      prop: 'unionid',
      label: '微信unionId',
      width: 170
    },
    {
      prop: 'openid',
      label: '微信openId',
      width: 175,
    },
    {
      prop: 'wx_external_userid',
      label: '企微外部联系人Id',
      width: 170,
    },
    {
      prop: 'created_at',
      label: '创建时间',
      width: 165,
    },
    {
      prop: 'operate',
      label: '操作',
      width: 295,
      fixed: 'right',
      isOperate: true,
      option: [
        {
          id: 0,
          name: '编辑',
          click: (row) => {
            if (row.type == 1) {
              rowid.value = row.id
              isEdit.value = true
              open.value = true
            }
          }
        },
        {
          id: 1,
          name: '分配',
          click: (row) => {
            rowid.value = row.id
            DepartRef.value.multiple = false
            DepartRef.value.departVisble = true
            whichOpen.value = 1
            DepartRef.value.selectedMember = [...singleStaff.value]
          }
        },
        {
          id: 1,
          name: '放弃',
          click: (row) => {
            isbatchDel.value = false
            rowid.value = row.id
            abandonDialog.title = `放弃【${row.name}】`
            abandonDialog.visible = true
            getReasonList()
          }
        },
        {
          id: 1,
          name: '流转记录',
          click: (row) => {
            clubopen.value = true
            rowid.value = row.id
            title.value = `【${row.clue_seas_name}】-【${row.name}/${row.mobile}】的流转记录`
          }
        },
        {
          id: 2,
          name: '删除',
          click: (row) => {
            alertTips.value = '您确定要删除' + row.name + '吗？'
            secondDialog.visible = true
            rowid.value = row.id
          }
        }
      ]
    }
  ]
  const searchOption = computed(() => {
    return [
      {
        label: '线索名称',
        name: 'name',
        value: '',
        type: 'input',
        placeholder: '请输入线索名称搜索'
      },
      {
        label: '线索手机',
        name: 'phone',
        value: '',
        type: 'input',
        placeholder: '请输入线索手机号搜索'
      },
      {
        label: '创建时间',
        name: 'create_time',
        value: [],
        type: 'datePicker',
        datePickerType: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期'
      },
      {
        label: '线索类型',
        name: 'type',
        value: '',
        type: 'select',
        placeholder: '全部',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            resolve([
              { name: '个人线索', id: 1 },
              { name: '企业线索', id: 2 }
            ])
          })
        },
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      }
    ]
  })
  const getids = () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(props.seaId)
      }, 1)
    })
  }
  const fetch = async () => {
    // 获取文件列表
    const seas_id = await getids()
    return [{ seas_id }, unassigned]
  }
  //查询
  const search = (v) => {
    state.searchParams = v
  }
  //清空
  const reset = () => {
    state.searchParams = deepCopy(defaultParams)
  }
  const personAdd = () => {
    open.value = false
    getSettings().then((res) => {
      if (!res.clue_type) {
        //未设置
        appDialog.visible = true
        clubChoose.value = 0
      } else if (res.clue_type == 1) {
        //设置为个人
        isEdit.value = false
        open.value = true
      } else {
        //设置为客户，还没有开发
      }
    })
  }
  const getDisaledColumn = () => {
    getDisaled().then((res) => {
      for (let key in res) {
        if (!res[key]) {
          tableOption.forEach((item, index) => {
            if (item.prop == key) {
              tableOption.splice(index, 1)
            }
          })
        }
      }
    })
  }
  getDisaledColumn()
  //获取放弃原因列表
  const getReasonList = () => {
    reasonList({ page: 1, page_size: 99 }).then((res) => {
      reasonListData.value = res.data
    })
  }
  const onSelectionChange = (data: any) => {
    selectid.value = getSetionId('id', data)
  }
  const batchdel = () => {
    isbatchDel.value = true
    getReasonList()
    abandonDialog.title = '批量放弃'
    abandonDialog.visible = true
  }
  // 获取部门成员
  const getDepart = (res: any) => {
    if (whichOpen.value == 1) {
      singleStaff.value = res
      assignData.work_user_list = getSetionId('id', singleStaff.value)
      assignData.clue_list = []
      assignData.clue_list.push(rowid.value)
      distribution(assignData).then((res: any) => {
        ElMessage.success('分配成功')
        reset()
        singleStaff.value = []
      })
    } else {
      batchStaff.value = res
      assignData.work_user_list = getSetionId('id', batchStaff.value)
      assignData.clue_list = selectid.value
      distribution(assignData).then((res: any) => {
        ElMessage.success('批量分配成功')
        reset()
        batchStaff.value = []
      })
    }
    DepartRef.value.departVisble = false
  }
  //批量分配
  const batchGive = () => {
    whichOpen.value = 2
    DepartRef.value.multiple = true
    DepartRef.value.departVisble = true
    DepartRef.value.selectedMember = [...batchStaff.value]
  }
  const close = () => {
    clubopen.value = false
    reset()
  }
  const closeNewClub = () => {
    open.value = false
  }
  const openExport = () => {
    isopenBatch.value = true
  }
  const submitData = () => {
    open.value = false
    reset()
  }
</script>
<style scoped lang="scss">
  .tiptext {
    text-align: center;
  }
  .abandon {
    display: flex;
    padding: 33px 0;
    img {
      width: 36px;
      height: 36px;
    }
    .photo {
      display: flex;
      align-items: center;
      margin-right: 5px;
    }
    .abandonstyle {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      :deep .el-form-item {
        margin-bottom: 0px;
      }
    }
  }

  .allcontent {
    padding: 24px 38px;
  }
  .content {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .both {
      border: 1px solid #ff6b00 !important;
    }
    .column {
      display: flex;
      flex-direction: column;
      align-items: center;
      border: 1px solid #eaeaea;
      border-radius: 4px;
      padding: 22px 40px;
      .text {
        margin-top: 11px;
        font-weight: 500;
        color: #33302d;
      }
    }
  }
</style>
